官方範例
import React, {useEffect, useRef} from 'react'
export default function App() {
const inref = useRef(0)
useEffect(()=>{
inref.current.focus()
},[])
return (
<div>
<input ref={inref} type='text' />
</div>
);
}
這邊是說當ref有觸發時,input會被focus
也就是說useRef 他是拿來當作DOM的工具,非常很方便
在寫一個範例
import React, {useState,useEffect, useRef} from 'react'
export default function App() {
const [name , setName] = useState('')
const inref = useRef(0)
useEffect(()=>{
// inref.current.focus()
inref.current = inref.current +1
})
return (
<div>
<input value={name} onChange={(e)=>setName(e.target.value)} />
<div>{name}</div>
<div>打了{inref.current}字元</div>
</div>
);
}
一個簡單的點擊事件
import React, {useEffect, useRef} from 'react'
export default function App() {
const inref = useRef()
function click(){
inref.current.innerHTML = '123456'
}
return (
<div>
<div ref={inref}></div>
<button onClick={click}>點我</button>
</div>
);
}